package org.fitweb.files;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static java.lang.System.getProperty;

public class FileMaker {

    private List<File> filesToDelete = new ArrayList<File>();

    public static File tempDir() {
        return new File(getProperty("java.io.tmpdir"));
    }

    public File file(File dir, String name) {
        return tempFile(new File(dir, name));
    }

    public File file(String name) {
        return tempFile(new File(name));
    }

    private File tempFile(File tempFile) {
        try {
            File parentFile = tempFile.getParentFile();
            if (parentFile != null && !parentFile.exists()) {
                directory(parentFile);
            }
            if (!tempFile.exists() && !tempFile.createNewFile()) {
                throw new IllegalStateException("Could not create: " + tempFile);
            }
        } catch (IOException e) {
            throw new IllegalStateException("Could not create: " + tempFile, e);
        }
        tempFile.deleteOnExit();
        filesToDelete.add(tempFile);
        return tempFile;
    }

    public File directory(File root) {
        return tempDir(root);
    }

    public File directory(File root, String branch) {
        return tempDir(new File(root, branch));
    }

    private File tempDir(File directory) {
        if (!directory.exists() && !directory.mkdirs()) {
            throw new IllegalStateException("Could not create: " + directory);
        }
        directory.deleteOnExit();
        filesToDelete.add(directory);
        return directory;
    }

    // Java sometimes fails to delete files marked with File.deleteOnExit(), so mop them up
    @Override protected void finalize() throws Throwable {
        super.finalize();
        Collections.reverse(filesToDelete);
        for (File file : filesToDelete) {
            if (file.exists() && !file.delete()) {
                System.err.println("Could not delete test file:" + file);
                throw new IllegalStateException("Could not delete test file: " + file);
            }
        }
    }
}
